Using while Loops in Java
Course: Core Java Training
Topic: Using while Loops
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy Official Website
1. Introduction to while Loops
A while loop is an iteration statement in Java that repeatedly executes a block of code as long as a specified condition evaluates to true. It is useful when the number of repetitions is not known in advance and depends on a condition.
For example, a program may continue asking a user to enter a valid password until the input meets the required criteria, process transactions until a queue is empty, or count down until a timer reaches zero.
Java supports several looping constructs, including while, do-while, and for. A while loop is an entry-controlled loop because Java checks its condition before executing the loop body.
2. Learning Objectives
- Understand the purpose and syntax of a
while loop.
- Learn how Java evaluates loop conditions.
- Use counters and update statements correctly.
- Apply
while loops to counting, validation, and calculation problems.
- Understand infinite loops and how to prevent them.
- Use
break and continue appropriately.
- Compare
while loops with other Java loops.
- Write, test, and debug practical Java programs that use iteration.
3. Syntax of a while Loop
The basic syntax of a while loop is:
while (condition) {
// Statements to execute repeatedly
// Update the variable or state
}
Explanation:
while is the Java keyword used to begin the loop.
condition is a Boolean expression that evaluates to true or false.
- The loop body executes whenever the condition is true.
- The update statement changes a variable or state so that the loop can eventually finish.
- When the condition becomes false, execution continues with the statement after the loop.
If the condition is false before the first iteration, the loop body does not execute at all.
4. How a while Loop Works
A while loop follows a repeated sequence of condition checking, execution, and updating.
- Initialize any required variables before the loop.
- Evaluate the condition.
- If the condition is true, execute the loop body.
- Update the counter or relevant program state.
- Return to the condition check.
- Stop when the condition becomes false.
The following flow represents the basic execution process:
Initialize variable
|
v
Check condition
|
+---+---+
| |
True False
| |
v v
Execute Exit loop
body
|
v
Update variable
|
+------> Check condition
5. Your First while Loop Program
The following program prints numbers from 1 to 5.
public class WhileExample {
public static void main(String[] args) {
int number = 1;
while (number <= 5) {
System.out.println(number);
number++;
}
}
}
Output:
1
2
3
4
5
Step-by-step explanation:
- The variable
number is initialized to 1.
- Java checks whether
number <= 5.
- If true, the current number is printed.
- The statement
number++ increases the value by one.
- The condition is checked again until the value becomes 6.
- When the condition is false, the loop terminates.
6. Understanding Initialization, Condition, and Update
Most counting loops require three important components: initialization, a condition, and an update.
| Component |
Example |
Purpose |
| Initialization |
int i = 1; |
Sets the starting value. |
| Condition |
i <= 10 |
Determines whether another iteration should occur. |
| Update |
i++; |
Changes the value so the loop can progress. |
In a while loop, initialization usually appears before the loop, while the update appears inside the body. Forgetting the update may cause an infinite loop when the condition remains true.
7. Printing Numbers Using while Loops
Example 1: Print Numbers from 1 to 10
public class PrintNumbers {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Example 2: Print Even Numbers from 2 to 20
public class EvenNumbers {
public static void main(String[] args) {
int number = 2;
while (number <= 20) {
System.out.println(number);
number += 2;
}
}
}
Output:
2
4
6
8
10
12
14
16
18
20
Increasing the value by 2 ensures that only even numbers are printed.
Example 3: Print Numbers in Reverse
public class ReverseCounting {
public static void main(String[] args) {
int number = 5;
while (number >= 1) {
System.out.println(number);
number--;
}
}
}
Output:
5
4
3
2
1
Reverse counting uses a decreasing counter. The condition and update must agree with the intended direction of counting.
8. Calculating the Sum of Numbers Using a while Loop
A while loop can repeatedly add values to a variable. This technique is useful in calculating totals, accumulating scores, processing quantities, and performing mathematical operations.
Example: Sum of Numbers from 1 to 10
public class SumNumbers {
public static void main(String[] args) {
int number = 1;
int sum = 0;
while (number <= 10) {
sum = sum + number;
number++;
}
System.out.println("Sum: " + sum);
}
}
Output:
Sum: 55
Explanation: The variable sum stores the accumulated total. Each iteration adds the current number to the total, then increases the number by one.
Understanding the Calculation
| Iteration |
Current Number |
Updated Sum |
| 1 |
1 |
1 |
| 2 |
2 |
3 |
| 3 |
3 |
6 |
| 4 |
4 |
10 |
| 5 |
5 |
15 |
| ... |
... |
... |
| 10 |
10 |
55 |
9. Multiplication Tables Using while Loops
Multiplication tables are a common exercise for understanding counters and repeated calculations.
Example: Table of 5
public class MultiplicationTable {
public static void main(String[] args) {
int number = 5;
int multiplier = 1;
while (multiplier <= 10) {
System.out.println(
number + " x " + multiplier + " = "
+ (number * multiplier)
);
multiplier++;
}
}
}
Output:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
You can change the value of number to generate another multiplication table. The loop continues until the multiplier becomes greater than 10.
10. Finding the Factorial of a Number
The factorial of a non-negative integer is the product of all positive integers up to that number. For example, the factorial of 5 is 120. The factorial of 0 is defined as 1.
Example Program
public class FactorialExample {
public static void main(String[] args) {
int number = 5;
int i = 1;
long factorial = 1;
while (i <= number) {
factorial = factorial * i;
i++;
}
System.out.println("Factorial: " + factorial);
}
}
Output:
Factorial: 120
Explanation: The program multiplies the factorial variable by each integer from 1 through 5. The long type supports larger values than int, but factorials grow quickly and can still exceed the capacity of a long.
Important Considerations
- Factorial is defined for non-negative integers in this context.
- For an input of zero, the loop does not execute and the initial value of 1 is returned.
- Negative inputs should be rejected before calculating a factorial.
- For large numbers, consider overflow and use a suitable approach such as
BigInteger when necessary.
11. Reversing a Number Using a while Loop
A while loop can process a number one digit at a time by using the remainder and integer division operators.
Example: Reverse 1234
public class ReverseNumber {
public static void main(String[] args) {
int number = 1234;
int reversed = 0;
while (number > 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number = number / 10;
}
System.out.println("Reversed number: " + reversed);
}
}
Output:
Reversed number: 4321
How it works:
number % 10 extracts the last digit.
reversed * 10 + digit appends that digit to the reversed number.
number / 10 removes the last digit through integer division.
- The loop stops when the remaining number becomes zero.
This basic example handles positive integers. Negative numbers, leading zeros in the reversed result, and integer overflow require additional consideration in a more complete solution.
12. Counting the Digits of a Number
Counting digits is another useful application of a while loop. The program repeatedly removes the last digit until no digits remain.
public class DigitCounter {
public static void main(String[] args) {
int number = 58372;
int temp = Math.abs(number);
int count = 0;
if (temp == 0) {
count = 1;
} else {
while (temp > 0) {
temp = temp / 10;
count++;
}
}
System.out.println("Number of digits: " + count);
}
}
Output:
Number of digits: 5
The temporary variable preserves the original number. The special check for zero is necessary because repeatedly dividing zero by 10 would not enter the loop.
Note that Math.abs() has an edge case for the minimum value of an int, which cannot be represented as a positive int. Production code should handle that case if arbitrary integer input is supported.
13. Reading User Input with a while Loop
A while loop can repeatedly read input until the user enters a sentinel value, such as zero or a specific command. This pattern is useful in interactive programs and simple menu-driven applications.
Example: Sum Numbers Until Zero Is Entered
import java.util.Scanner;
public class SumUntilZero {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
System.out.println("Enter integers (0 to stop):");
while (scanner.hasNextInt()) {
int number = scanner.nextInt();
if (number == 0) {
break;
}
sum += number;
}
System.out.println("Total sum: " + sum);
scanner.close();
}
}
Sample Input:
10
20
5
0
Output:
Enter integers (0 to stop):
Total sum: 35
The program continues while integer input is available. Entering zero stops the loop, and the zero is not added to the total. If a non-integer token is entered, hasNextInt() returns false and the loop ends.
14. Using while Loops for Input Validation
Input validation often requires repeating a prompt until the user provides an acceptable value. A while loop is useful because the number of attempts may not be known in advance.
Example: Accept a Positive Number
import java.util.Scanner;
public class PositiveNumberInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
System.out.print("Enter a positive integer: ");
while (true) {
if (!scanner.hasNextInt()) {
System.out.println("Invalid input. Enter a whole number.");
scanner.next();
} else {
number = scanner.nextInt();
if (number > 0) {
break;
}
System.out.println("Number must be greater than zero.");
}
System.out.print("Try again: ");
}
System.out.println("Accepted number: " + number);
scanner.close();
}
}
Sample Interaction:
Enter a positive integer: -4
Number must be greater than zero.
Try again: abc
Invalid input. Enter a whole number.
Try again: 12
Accepted number: 12
The loop uses break when a valid positive integer is received. Invalid text is consumed using scanner.next() so that the same token does not cause an endless validation cycle.
15. Understanding Infinite while Loops
An infinite loop is a loop that does not terminate under its current execution conditions. It can occur intentionally in continuously running systems, but it can also result from a programming mistake.
Example of an Unintentional Infinite Loop
int i = 1;
while (i <= 5) {
System.out.println(i);
// The update statement is missing.
}
Because i remains 1, the condition i <= 5 remains true. The program continues printing 1 indefinitely until it is stopped.
Corrected Version
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
Common Causes of Infinite Loops
- Forgetting to update the counter.
- Updating the counter in the wrong direction.
- Using a condition that never becomes false.
- Accidentally resetting a variable inside the loop.
- Using a sentinel loop without checking the stopping value correctly.
Always identify how the loop progresses and why its termination condition will eventually become false. For intentionally continuous loops, such as event processing, include an appropriate shutdown or exit mechanism.
16. Using break to Exit a while Loop
The break statement immediately terminates the nearest enclosing loop. It is useful when the program discovers a stopping condition before reaching the loop's regular condition check.
Example: Stop at Number 4
public class BreakExample {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
if (i == 4) {
break;
}
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
When i becomes 4, the break statement exits the loop before 4 is printed.
17. Using continue in a while Loop
The continue statement skips the remaining statements in the current iteration and moves to the next condition check. In a while loop, you must ensure that the counter update still occurs when necessary.
Example: Print Odd Numbers from 1 to 10
public class ContinueExample {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
i++;
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
}
}
Output:
1
3
5
7
9
The counter is incremented before the condition that may execute continue. This ensures that even-numbered iterations do not cause the loop to repeat forever.
18. Nested while Loops
A nested while loop is a while loop inside another while loop. It is useful for working with rows and columns, simple patterns, grids, and combinations of repeated operations.
Example: Print a Rectangle of Stars
public class StarPattern {
public static void main(String[] args) {
int row = 1;
while (row <= 3) {
int column = 1;
while (column <= 4) {
System.out.print("* ");
column++;
}
System.out.println();
row++;
}
}
}
Output:
* * * *
* * * *
* * * *
The outer loop controls the rows, while the inner loop prints four stars for each row. The inner counter is reset at the beginning of every outer iteration.
19. Difference Between while and do-while Loops
Both loops repeat statements while a condition permits, but they evaluate the condition at different points.
| Feature |
while Loop |
do-while Loop |
| Condition check |
Before the loop body |
After the loop body |
| Minimum executions |
Zero |
One |
| Loop type |
Entry-controlled |
Exit-controlled |
| Common use |
Repeat while a condition is true |
Execute at least once, then decide whether to repeat |
| Syntax ending |
No semicolon after the condition's closing parenthesis |
Semicolon required after the condition |
Example: while Loop with a False Condition
int number = 10;
while (number < 5) {
System.out.println(number);
}
Output: No output, because the condition is false at the first check.
Equivalent do-while Example
int number = 10;
do {
System.out.println(number);
} while (number < 5);
Output:
10
The do-while loop executes its body once before checking the condition. Choose the loop type that best matches the requirements.
20. Difference Between while and for Loops
| Feature |
while Loop |
for Loop |
| Structure |
Initialization and update are generally separate from the condition. |
Initialization, condition, and update are placed in the loop header. |
| Best suited for |
Condition-based repetition where the iteration count may be unknown. |
Counter-based repetition where the iteration pattern is clear. |
| Readability |
Useful when loop control depends on changing program state. |
Often concise for a known range of iterations. |
| Execution |
Checks the condition before each iteration. |
Checks the termination condition before each iteration. |
Both constructs can solve many of the same problems. Select the one that makes the intended repetition easiest to understand and maintain.
21. Practical Applications of while Loops
| Application |
How a while Loop Helps |
| ATM simulation |
Repeats a menu until the user chooses to exit. |
| Input validation |
Requests another value until the input satisfies the rules. |
| Number processing |
Extracts digits until the remaining number becomes zero. |
| Game development |
Repeats game actions while the game remains active. |
| Inventory processing |
Processes items while unprocessed items remain. |
| Data processing |
Reads records until the end of the input is reached. |
| Countdown timer |
Decreases a counter until it reaches the stopping value. |
| Menu-driven programs |
Continues displaying options until an exit condition is met. |
22. Common Errors and Troubleshooting
| Problem |
Cause |
Solution |
| Loop never starts |
The condition is false initially. |
Check the initial variable values and the condition. |
| Loop never ends |
The condition remains true. |
Check that variables progress toward termination. |
| One extra iteration |
The comparison operator is incorrect. |
Review whether to use < or <=. |
| Wrong total |
The accumulation statement is missing or misplaced. |
Update the total inside the correct iteration. |
| Unexpected output |
The update occurs before or after the wrong operation. |
Trace each iteration and check statement order. |
| Input repeats endlessly |
Invalid input was not consumed. |
Consume invalid tokens or handle the input error appropriately. |
| Nested loop prints the wrong pattern |
The inner counter is not reset correctly. |
Initialize the inner counter for each outer iteration. |
23. Best Practices for Using while Loops
- Initialize loop variables before the loop when appropriate.
- Use a Boolean condition that clearly expresses the stopping rule.
- Ensure the loop makes progress toward termination.
- Use braces to make the loop body easy to read.
- Avoid modifying the loop-control variable in several unrelated places.
- Use meaningful variable names instead of unclear identifiers.
- Validate user input when the loop depends on data supplied by a user.
- Test the first iteration, last iteration, and cases where the loop executes zero times.
- Use
break and continue when they make the logic clearer, not as a substitute for a well-designed condition.
- Consider integer overflow when counters or accumulated values can become very large.
- Close resources such as a
Scanner when appropriate, especially when the program owns the underlying resource.
24. Practice Exercises
Beginner Exercises
- Print numbers from 1 to 20 using a
while loop.
- Print all even numbers from 2 to 50.
- Print numbers from 10 down to 1.
- Calculate the sum of all integers from 1 to 100.
- Generate the multiplication table of a number.
Intermediate Exercises
- Calculate the factorial of a non-negative integer.
- Count the digits in an integer.
- Reverse the digits of a positive integer.
- Determine whether a number is a palindrome.
- Keep accepting integers until the user enters zero, then display their sum.
- Print all numbers between 1 and 100 that are divisible by both 3 and 5.
Advanced Exercises
- Build a menu-driven calculator that continues until the user chooses to exit.
- Create a password-validation exercise with a limited number of attempts.
- Use nested
while loops to display a triangle or rectangle pattern.
- Calculate a simple bill by repeatedly accepting item prices until a sentinel value is entered.
- Develop a number-guessing game that repeats until the user guesses correctly or chooses to quit.
25. Mini Project: Menu-Driven Number Utility
Objective: Build a Java application that repeatedly displays a menu and lets users perform simple number operations until they choose to exit.
Project Requirements
- Display a menu containing options to print numbers, calculate a sum, and exit.
- Use a
while loop to repeat the menu.
- Use a
switch statement to handle the selected option.
- Validate menu input and handle unsupported options.
- Terminate the loop when the user chooses the exit option.
Sample Implementation
import java.util.Scanner;
public class NumberUtility {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean running = true;
while (running) {
System.out.println("\n--- Number Utility ---");
System.out.println("1. Print numbers from 1 to N");
System.out.println("2. Calculate sum from 1 to N");
System.out.println("3. Exit");
System.out.print("Choose an option: ");
if (!scanner.hasNextInt()) {
System.out.println("Please enter a valid integer option.");
scanner.next();
continue;
}
int choice = scanner.nextInt();
switch (choice) {
case 1:
case 2:
System.out.print("Enter a positive integer N: ");
if (!scanner.hasNextInt()) {
System.out.println("Invalid number.");
scanner.next();
break;
}
int n = scanner.nextInt();
if (n <= 0) {
System.out.println("N must be positive.");
break;
}
int i = 1;
long sum = 0;
while (i <= n) {
if (choice == 1) {
System.out.println(i);
}
sum += i;
i++;
}
if (choice == 2) {
System.out.println("Sum: " + sum);
}
break;
case 3:
running = false;
System.out.println("Exiting the program.");
break;
default:
System.out.println("Choose an option from 1 to 3.");
}
}
scanner.close();
}
}
What This Project Teaches
- Repeating a menu with a
while loop.
- Using a Boolean variable to control program execution.
- Combining
while and switch statements.
- Handling invalid menu input.
- Using a counter and accumulator for number calculations.
26. Interview Questions and Answers
Q1. What is a while loop in Java?
Answer: A while loop repeatedly executes a statement or block while its Boolean condition remains true.
Q2. Is a while loop entry-controlled or exit-controlled?
Answer: It is entry-controlled because Java checks the condition before executing the loop body.
Q3. Can a while loop execute zero times?
Answer: Yes. If the condition is false during the first evaluation, the loop body is skipped.
Q4. What causes an infinite while loop?
Answer: An infinite loop can occur when its condition never becomes false, often because the loop-control variable is not updated correctly.
Q5. What is the purpose of break?
Answer: The break statement immediately exits the nearest enclosing loop or switch statement.
Q6. What is the purpose of continue?
Answer: The continue statement skips the rest of the current iteration and proceeds to the next loop-condition check.
Q7. What is the difference between while and do-while?
Answer: A while loop checks its condition before execution and may execute zero times. A do-while loop checks its condition afterward and executes at least once.
Q8. Can a while loop be nested?
Answer: Yes. One while loop can appear inside another. The outer loop commonly controls rows or groups, while the inner loop controls repeated operations within each group.
Q9. When should a while loop be preferred over a for loop?
Answer: A while loop is often suitable when repetition depends on a changing condition and the number of iterations is not known beforehand.
Q10. How can an infinite loop be prevented?
Answer: Check the condition, initialization, update statements, and all paths through the loop body. Ensure that the loop has a valid termination condition or an intentional exit mechanism.
27. Quick Revision Checklist
- A
while loop repeats code while a condition is true.
- The condition is evaluated before each iteration.
- Initialization generally occurs before the loop.
- The loop body should update relevant variables or program state.
- A false initial condition results in zero iterations.
- Use counters to control repetition and accumulators to calculate totals.
- Use
break to exit and continue to skip to the next iteration.
- Nested loops support repeated operations across rows, columns, or groups.
- Validate input and handle stopping values carefully.
- Test termination conditions and boundary cases to avoid logical errors.
28. Conclusion
The while loop is an important part of Core Java because it allows programs to repeat operations based on conditions. It is useful for counting, calculations, number processing, input validation, menu-driven programs, and many other tasks where the number of iterations may not be known in advance.
To use while loops effectively, understand the condition, initialize variables correctly, update the program state, and verify that the loop can terminate. Practice with counting problems, factorials, digit operations, input validation, and small projects to build confidence in Java iteration.
Continue learning with the Core Java Training Course, register for a course demo, or visit the JustAcademy official website.